package com.leet.code.thread;

import java.util.concurrent.Semaphore;

public class Code1117 {
    public static void main(String[] args) {
        H2O h2O = new H2O();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    h2O.hydrogen(()-> System.out.print("H"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    h2O.oxygen(()-> System.out.print("O"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    static class H2O {

        public H2O() {

        }

        private Semaphore h = new Semaphore(2);
        private Semaphore o = new Semaphore(1);


        public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
            h.acquire();
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();
            o.release();
        }

        public void oxygen(Runnable releaseOxygen) throws InterruptedException {
            o.acquire(2);
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
            releaseOxygen.run();
            h.release(2);
        }
    }

}
